package com.rjs.nio.channel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

/**
 * 线程之间通过管道通信
 * @author LiuZhenghua
 * 2017年12月12日 下午4:26:15
 */
public class PipeDemo {

	public static void main(String[] args) throws IOException, InterruptedException {
		final Pipe pipe = Pipe.open();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				ByteBuffer byteBuffer = ByteBuffer.allocate(128);
				byteBuffer.put("hello world!".getBytes());
				byteBuffer.flip();
				
				SinkChannel sinkChannel = pipe.sink();
				try {
					sinkChannel.write(byteBuffer);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
//				ByteBuffer byteBuffer = ByteBuffer.allocate(128);
				ByteBuffer byteBuffer = ByteBuffer.allocate(2);
				SourceChannel sourceChannel = pipe.source();
				try {
					byte[] b = new byte[2048];
					int b_len = 0;
					int len = -1;
					while ((len = sourceChannel.read(byteBuffer)) > 0) {
						byteBuffer.flip();
						while(byteBuffer.hasRemaining()) {
//							System.out.print((char)byteBuffer.get());
							byteBuffer.get(b, b_len, len);
							b_len += len;
						}
						byteBuffer.clear();
					}
					System.out.println(new String(b, 0, b_len));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		Thread.sleep(1000);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				ByteBuffer byteBuffer = ByteBuffer.allocate(128);
				byteBuffer.put("你好呀".getBytes());
				byteBuffer.flip();
				
				SinkChannel sinkChannel = pipe.sink();
				try {
					sinkChannel.write(byteBuffer);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
